package com.neuedu.corejava.ch9;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateClass {

	public static void main(String[] args) {
		// 获取当期系统时间
		Date date = new Date();
		System.out.println(date.getTime());
		long time = System.currentTimeMillis();// unix - 在有些数据库设计中，使用long保存时间
		System.out.println(time);

		date = new Date(time);
		System.out.println(date);

		//java.util.Date没有提供时间计算方法，时间一般使用Calendar进行计算
		// 日历
		Calendar calendar = Calendar.getInstance();
		// 取年份
		String dateString = "" + calendar.get(Calendar.YEAR);
		System.out.println(dateString);

		// 取月份
		dateString = "" + (calendar.get(Calendar.MONTH) + 1);
		System.out.println(dateString);

		// 取日
		dateString = "" + calendar.get(Calendar.DATE);
		System.out.println(dateString);

		// 取星期
		dateString = "" + (calendar.get(Calendar.DAY_OF_WEEK) - 1);
		System.out.println(dateString);

		// 取小时
		// 12小时
		dateString = "" + calendar.get(Calendar.HOUR);
		System.out.println(dateString);
		// 24小时
		dateString = "" + calendar.get(Calendar.HOUR_OF_DAY);
		System.out.println(dateString);

		// 取分钟
		dateString = "" + calendar.get(Calendar.MINUTE);
		System.out.println(dateString);

		// 取秒钟
		dateString = "" + calendar.get(Calendar.SECOND);
		System.out.println(dateString);

		// 取毫秒
		dateString = "" + calendar.get(Calendar.MILLISECOND);
		System.out.println(dateString);

		// 时间的计算
		// 3天后
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 3);
		System.out.println(calendar.get(Calendar.DATE));

		// 3月前
		calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 3);
		System.out.println(calendar.get(Calendar.MONTH) + 1);

		// 5年后
		calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) +5);
		System.out.println(calendar.get(Calendar.YEAR));
		
		//时间与时间字符串之间的转换
		//2018-8-8 8 ：8 : 8：888
		String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
		//HH-->表示24小时 SSS--》表示毫秒
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		
		try {
			date = sdf.parse("2008-8-8 8:8:8.888");
			System.out.println(date);
			
			pattern = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒 EE";
			sdf.applyPattern(pattern);
			String dateString2 = sdf.format(date);
			System.out.println(dateString2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
